package erz.printing.police;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.pdf.PdfRenderer;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import erz.printing.police.print.PdfAssetPrintAdapter;
import erz.printing.police.utils.AndroidBug5497Workaround;

public class DocumentActivity extends BaseActivity {

    private WebView webView;

    private ImageView imageView;
    private ParcelFileDescriptor pdfFd;
    private PdfRenderer pdfRenderer;
    private String pdfAssetPath;
    private int curPageIndex;
    private boolean isPdfDocment = false;
    private TextView pageIndicator;

    // 手势滑动翻页
    private GestureDetector mDetector;
    private GestureListener mGestureListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_document);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        fixPlaceHolderHeight();

        initView();

        AndroidBug5497Workaround.assistActivity(this);
    }

    private void fixPlaceHolderHeight() {
        int height = getActionBarHeight() + getStatusBarHeight();
        View view = findViewById(R.id.place_holder);
        ViewGroup.LayoutParams lp = view.getLayoutParams();
        lp.height = height;
        view.setLayoutParams(lp);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case R.id.document_print:
                if (isPdfDocment) {
                    printPdfDocument();
                } else {
                    printHtmlDocument();
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void initView() {
        webView = findViewById(R.id.document_webview);
        webView.setWebViewClient(new WebViewClient(){
            public boolean shouldOverrideUrlLoading(WebView webView, String url) {
                webView.loadUrl(url);
                return true;
            }
        });
        imageView = findViewById(R.id.document_pdfimage);
        pageIndicator = findViewById(R.id.page_indicator);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String docTemplate = bundle.getString("docTemplate");
            if (docTemplate != null && docTemplate.length() > 0) {
                if (docTemplate.endsWith(".pdf")) {
                    isPdfDocment = true;
                    pdfAssetPath = docTemplate;
                    webView.setVisibility(View.GONE);
                    pageIndicator.setVisibility(View.VISIBLE);
                    showPdf(docTemplate);
                    initGesture();
                }
                else {
                    String docmentPath = "file:///android_asset/doctemplates/" + docTemplate;
                    imageView.setVisibility(View.GONE);
                    webView.loadUrl(docmentPath);
                }
            }
            else {
                imageView.setVisibility(View.GONE);
                webView.loadUrl("file:///android_asset/test.html");
            }

            String title = bundle.getString("title");
            if (title != null && title.length() > 0) {
                ActionBar actionBar = getSupportActionBar();
                actionBar.setTitle(title);
            }
        }
    }

    @TargetApi(21)
    private void updatePageIndicator() {
        int pageCount = pdfRenderer.getPageCount();
        String strIndicator = "第" + (curPageIndex+1) + "/" + pageCount + "页(左右滑动翻页)";
        pageIndicator.setText(strIndicator);
    }

    @TargetApi(21)
    private void showPdfPrevPage() {
        if (curPageIndex > 0) {
            curPageIndex--;
            Bitmap bitmap = getPdfBitmapByPage(pdfRenderer, curPageIndex);
            imageView.setImageBitmap(bitmap);

            updatePageIndicator();
        }
    }

    @TargetApi(21)
    private void showPdfNextPage() {
        int pageCount = pdfRenderer.getPageCount() - 1;
        if (curPageIndex < pageCount) {
            curPageIndex++;
            Bitmap bitmap = getPdfBitmapByPage(pdfRenderer, curPageIndex);
            imageView.setImageBitmap(bitmap);

            updatePageIndicator();
        }
    }

    private void showPdf(String fileName) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            imageView.setImageResource(R.mipmap.nopdfpreview);
        }
        else {
            try {
                pdfRenderer = openRenderer(fileName);
                curPageIndex = 0;
                Bitmap bitmap = getPdfBitmapByPage(pdfRenderer, curPageIndex);
                imageView.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }

            updatePageIndicator();
        }
    }

    @TargetApi(21)
    private PdfRenderer openRenderer(String fileName) throws IOException {
        File file = new File(getCacheDir(), fileName);
        if (!file.exists()) {
            File tmp = file.getParentFile();
            if (!tmp.exists()) {
                tmp.mkdirs();
            }
            InputStream asset = getAssets().open(fileName);
            FileOutputStream output = new FileOutputStream(file);
            final byte[] buffer = new byte[4096];
            int size;
            while ((size = asset.read(buffer)) != -1) {
                output.write(buffer, 0, size);
            }
            asset.close();
            output.close();
        }
        pdfFd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
        return new PdfRenderer(pdfFd);
    }

    @TargetApi(21)
    private Bitmap getPdfBitmapByPage(PdfRenderer pdfRenderer, int index) {
        PdfRenderer.Page page = pdfRenderer.openPage(index);
        Bitmap bitmap = Bitmap.createBitmap(page.getWidth(), page.getHeight(), Bitmap.Config.ARGB_8888);
        page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
        page.close();
        return bitmap;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.document_option_menu, menu);
        return true;
    }

    private void printHtmlDocument() {
        PrintManager printManager = (PrintManager)getSystemService(Context.PRINT_SERVICE);
        String jobName = "法律文书";
        PrintDocumentAdapter printAdapter;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            printAdapter = webView.createPrintDocumentAdapter(jobName);
        } else {
            printAdapter = webView.createPrintDocumentAdapter();
        }
        PrintAttributes attrs = new PrintAttributes.Builder()
                .setMediaSize(PrintAttributes.MediaSize.ISO_A4)
                .setColorMode(PrintAttributes.COLOR_MODE_MONOCHROME)
                /*.setResolution(new PrintAttributes.Resolution("dpi72", "dpi72", 72, 72))
                .setMinMargins(new PrintAttributes.Margins(0,0,0,0))*/
                .build();
        printManager.print(jobName, printAdapter, attrs);
    }

    private void printPdfDocument() {
        PrintManager printManager = (PrintManager)getSystemService(Context.PRINT_SERVICE);
        String jobName = "法律文书";
        PrintDocumentAdapter printAdapter = new PdfAssetPrintAdapter(pdfAssetPath, this);
        PrintAttributes attrs = new PrintAttributes.Builder()
                .setMediaSize(PrintAttributes.MediaSize.ISO_A4)
                .setColorMode(PrintAttributes.COLOR_MODE_MONOCHROME)
                /*.setResolution(new PrintAttributes.Resolution("dpi72", "dpi72", 72, 72))
                .setMinMargins(new PrintAttributes.Margins(0,0,0,0))*/
                .build();
        printManager.print(jobName, printAdapter, attrs);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isPdfDocment) {
            if (pdfRenderer != null) pdfRenderer.close();
            if (pdfFd != null) {
                try {
                    pdfFd.close();
                } catch (IOException e) {
                }
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mDetector != null) {
            return mDetector.onTouchEvent(event);
        }
        return false;
    }

    private void initGesture() {
        mGestureListener = new GestureListener();
        mDetector = new GestureDetector(this, mGestureListener);
    }

    private class GestureListener implements GestureDetector.OnGestureListener {
        @Override
        public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float vx, float vy) {
            //Log.i("aaa", "e=" + motionEvent + ", e1=" + motionEvent1 + ", v=" + vx + ", v1=" + vy);
            if (motionEvent.getPointerCount() == 1) {
                float dx = motionEvent1.getX() - motionEvent.getX();
                float dy = motionEvent1.getY() - motionEvent.getY();
                dx = Math.abs(dx);
                dy = Math.abs(dy);
                double angle = Math.atan(dy / dx);
                if (angle * 5 < 3.14) {
                    if (vx > 0) {
                        // 从左到右，上一页
                        showPdfPrevPage();
                    }
                    else {
                        // 下一页
                        showPdfNextPage();
                    }
                }
            }
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
            return false;
        }

        @Override
        public void onShowPress(MotionEvent motionEvent) {

        }

        @Override
        public boolean onDown(MotionEvent motionEvent) {
            return false;
        }

        @Override
        public boolean onSingleTapUp(MotionEvent motionEvent) {
            return false;
        }

        @Override
        public void onLongPress(MotionEvent motionEvent) {

        }
    }
}
